package team.bluepen.supermarket.data.entity;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import team.bluepen.supermarket.kafka.KafkaDeserializer;
import team.bluepen.supermarket.kafka.KafkaSerializer;

import java.beans.ConstructorProperties;
import java.io.Serializable;

/**
 * @author RollW
 */
public class ProductNameStatusAmount implements Serializable {
    @JsonProperty("name")
    private final String name;

    @JsonProperty("activeCount")
    private final int activeCount;

    @JsonProperty("inactiveCount")
    private final int inactiveCount;

    @ConstructorProperties({"name", "activeCount", "inactiveCount"})
    public ProductNameStatusAmount(String name, int activeCount, int inactiveCount) {
        this.name = name;
        this.activeCount = activeCount;
        this.inactiveCount = inactiveCount;
    }

    public String getName() {
        return name;
    }

    public int getActiveCount() {
        return activeCount;
    }

    public int getInactiveCount() {
        return inactiveCount;
    }

    public static ProductNameStatusAmount add(ProductNameStatusAmount a, ProductNameStatusAmount b) {
        return new ProductNameStatusAmount(a.getName(),
                a.getActiveCount() + b.getActiveCount(),
                a.getInactiveCount() + b.getInactiveCount());
    }

    public static ProductNameStatusAmount of(Product product) {
        return new ProductNameStatusAmount(product.getName(),
                product.isState() ? product.getAmount() : 0,
                product.isState() ? 0 : product.getAmount());
    }

    public static KafkaSerializer<ProductNameStatusAmount> serializer() {
        return Serial.INSTANCE;
    }

    public static KafkaDeserializer<ProductNameStatusAmount> deserializer() {
        return Serial.INSTANCE;
    }

    private static class Serial implements KafkaSerializer<ProductNameStatusAmount>,
            KafkaDeserializer<ProductNameStatusAmount> {
        private final ObjectMapper objectMapper = new ObjectMapper();

        @Override
        public String serialize(ProductNameStatusAmount productNameStatusAmount) {
            try {
                return objectMapper.writeValueAsString(productNameStatusAmount);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public ProductNameStatusAmount deserialize(String s) {
            try {
                return objectMapper.readValue(s, ProductNameStatusAmount.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        static final Serial INSTANCE = new Serial();
    }
}
